package com.qyer.lxp.action;

import com.qyer.lxp.common.framework.contants.QyerContants;
import com.qyer.lxp.common.framework.httpclient.HttpClientUtil;
import com.qyer.lxp.common.framework.util.Md5Encrypt;
import com.qyer.lxp.common.framework.util.QyerConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiangping on 16/5/5.
 */
public class HttpClientUtil_test {

    static final Logger logger = Logger.getLogger(HttpClientUtil_test.class);

    private static String url = "http://api.lixing.biz/service?method=";
    private static String user = "C100000362";
    private static String key = "4a071cd838d7fbeec1225dd7d125be3a";
    private static PoolingClientConnectionManager pccm = null;

    static
    {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

        pccm = new PoolingClientConnectionManager(schemeRegistry);
        try
        {
            pccm.setMaxTotal(QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_MAX_TOTAL, 500));
        } catch (NumberFormatException e)
        {
            logger.error("Key[httpclient.max_total] Not Found in systemConfig.properties", e);
        }
        // 每条通道的并发连接数设置（连接池）
        try
        {
            pccm.setDefaultMaxPerRoute(QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_PER_ROUTE_MAX_TOTAL, 2000));
        } catch (NumberFormatException e)
        {
            logger.error("Key[httpclient.default_max_connection] Not Found in systemConfig.properties", e);
        }
    }

    public static HttpClient getHttpClient()
    {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_TIME_OUT, 5000)); // 5000ms
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_TIME_OUT, 5000));
        params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");
        params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "utf-8");
        return new DefaultHttpClient(pccm, params);
    }
    public static String requestPost(String methodName,String param){
        HttpClient httpclient = getHttpClient();
        String result = "";
        try {
            HttpPost httppost = new HttpPost(url+methodName);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            String sign = Md5Encrypt.md5(StringUtils.isNotBlank(param)?"para" + param + key:key);
            if(StringUtils.isNotBlank(param)) {
                nvps.add(new BasicNameValuePair("para", param));
            }
            nvps.add(new BasicNameValuePair("user", user));
            nvps.add(new BasicNameValuePair("sign", sign));
            httppost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                result = EntityUtils.toString(resEntity);
            } else {
                logger.error(
                        "调用远程服务器出错"
                                + response);
            }

        } catch (Exception e) {
            logger.error("调用外部HTTP方式提交到主站代码执行异常", e);
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {
            }
        }
        return  result;
    }

    public static void main(String[] args) {

//        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><product-code-search-request><update-date-start>2016-05-01</update-date-start><update-date-end>2016-05-30</update-date-end><start>1</start><end>10</end></product-code-search-request>";
//        try {
//            String result = HttpClientUtil.requestPost("getUpdateProductInfo",xml);
//            System.out.println(result);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<product-detail-request>\n" +
                "\t\t<product-code>S01ES04S0b211</product-code>\n" +
                "\t\t<currency>CNY</currency>\t\t\n" +
                "\t\t<need-sale-info>true</need-sale-info>\t\t\n" +
                "</product-detail-request>\n";
        try {
            String result = HttpClientUtil.requestPost("getProductDetail",xml);
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }



        //获取销售code
//        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
//                "<sale-item-info-request>\n" +
//                "\t\t<product-code>D3vJP0AD00c67</product-code>\n" +
//                "\t\t<currency>CNY</currency>\n" +
//                "</sale-item-info-request>\n";
//        try {
//            String result = HttpClientUtil_test.requestPost("getSaleItemInfo", xml);
//            System.out.println(result);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        //获取销售产品详细信息
//        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
//                "<sale-item-detail-request>\n" +
//                "\t\t<sale-codes>\n" +
//                "\t\t\t<sale-code>S0196e392</sale-code><!--可重复节点-->\n" +
//                "\t\t</sale-codes>\n" +
//                "<currency>CNY</currency>\n" +
//                "\t</sale-item-detail-request>\n";
//        try {
//            String result = HttpClientUtil.requestPost("getSaleItemDetail",xml);
//            System.out.println(result);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        //获取产品价格日历
//        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
//                "<period-price-query-request>\n" +
//                "<product-code>S01ES04S0b211</product-code>\n" +
//                "\t\t<travel-date>2016-05-10</travel-date>\n" +
//                "<travel-date-end>2016-05-15</travel-date-end>\n" +
//                "<currency>CNY</currency>\n" +
//                "\t</period-price-query-request>\n";
//        try {
//            String result = HttpClientUtil.requestPost("getPriceByPeriod",xml);
//            System.out.println(result);
//        }catch (Exception e){
//            e.printStackTrace();
//        }


//        String xml = "";
//        try {
//            String result = HttpClientUtil.requestPost("searchProductCount", xml);
//            System.out.println(result);
//        }catch (Exception e){
//            e.printStackTrace();
//        }


    }
}
